package com.ideal.hadoopadmin.common.framework.orm;

import com.ideal.hadoopadmin.common.util.ReflectUtils;
import com.ideal.hadoopadmin.service.main.SystemMenuService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class SearchFilter {
    private static final Logger logger = LoggerFactory.getLogger(SearchFilter.class);
    public enum Operator {
        EQ, LIKE, GT, LT, GTE, LTE, IN, NEQ, ISNULL
    }

    private String fieldName;
    private Object value;
    private Operator operator;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.value = value;
        this.operator = operator;
    }

    public SearchFilter(String fieldName, Operator operator) {
        this.fieldName = fieldName;
        this.operator = operator;
    }


    /**
     * searchParams中key的格式为OPERATOR_FIELDNAME
     */
    public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();

        for (Entry<String, Object> entry : searchParams.entrySet()) {
            // 过滤掉空值
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String && StringUtils.isBlank((String) value)) {
                continue;
            }

            // 拆分operator与filedAttribute
            String[] names = StringUtils.split(key, "_");
            if (names.length != 2) {
                continue;
                // throw new IllegalArgumentException(key + " is not a valid search filter name");
            }
            String filedName = names[1];
            Operator operator = Operator.valueOf(names[0]);

            // 创建searchFilter
            SearchFilter filter = new SearchFilter(filedName, operator, value);
            filters.put(key, filter);
        }
        return filters;
    }

    /**直接获取 where String **/
    public static String parseToString(Map<String, Object> searchParams){
        StringBuffer where = new StringBuffer();
        Map<String, SearchFilter> filters=SearchFilter.parse(searchParams);
        if(filters==null||filters.isEmpty()){
            return null;
        }
        /**  **/
        for(Map.Entry<String,SearchFilter> entry: filters.entrySet()){
            SearchFilter filter=entry.getValue();
            String filename=filter.getFieldName();
            //解析实体类中的 嵌套  这里直接替换掉变量中的点 （这需要表字段在命名的时候 外键都是表名加字段名）
//            String[] names=filename.split("\\.");
//            if(names.length==2){
//                filename=names[1];
//            }
//            filename=filename.replaceAll("\\.","");

            Object value=filter.getValue();
            value=processValue(filter.getOperator(),value);

            //这里是都是用的最常见的情况 如果有特殊 需要特殊分析
            switch (filter.getOperator()) {
                case ISNULL:
                    where.append(filename+" is null and ");
                    break;
                case EQ:
                    where.append(filename + " = "+value+" and ");
                    break;
                case LIKE:
                    where.append(filename + " like '%" + value + "%' and ");
                    break;
                case GT:
                    where.append(filename + " > " + value + " and ");
                    break;
                case LT:
                    where.append(filename + " < " + value + " and ");
                    break;
                case GTE:
                    where.append(filename + " >= " + value + " and ");
                    break;
                case LTE:
                    where.append(filename + " <= " + value + " and ");
                    break;
                case IN:
                    where.append(filename + " in ("+value+") and ");
                    break;
                case NEQ:
                    where.append(filename + " <> "+value+" and ");
                    break;
            }
        }
        String whereStr=where.toString();
        if(whereStr.endsWith(" and ")){
            whereStr=whereStr.substring(0,whereStr.length()-4);
        }
        return whereStr;

    }


    public String getFieldName() {
        return fieldName;
    }

    public Object getValue() {
        return value;
    }

    public Operator getOperator() {
        return operator;
    }

    public String toString() {
        return ReflectUtils.fieldsToString(this);
    }


    public static String processValue(Operator operator,Object val){

        //处理 in
        val=processInOperator(val);

        if(val instanceof String){
            if(operator.equals(Operator.LIKE)||operator.equals(Operator.IN)){

            }else {
                val = "'" + val + "'";
            }
        }

        return val+"";
    }

    public static Object processInOperator(Object value){
        String finalVal="";
        if (value instanceof Collection){
            Iterator iterator=((Collection) value).iterator();
            while(iterator.hasNext()){
                Object item=iterator.next();
                if(item instanceof String){
                    finalVal=finalVal+"'"+item+"',";
                }else{
                    finalVal=finalVal+item+",";
                }
            }

        }else{
            return value;
        }
        finalVal=finalVal.endsWith(",")?finalVal.substring(0,finalVal.length()-1):finalVal;
        return finalVal;
    }
}